package com.anlogic.sdk.openocd.model;

import java.util.ArrayList;
import java.util.List;

import com.google.gson.Gson;

public class TargetModel {
	private List<RemoteTarget> targets = new ArrayList<>();
	
	public List<RemoteTarget> getTargets() {
		return this.targets;
	}
	
	public String[] getTargetNames() {
		List<String> targetNames = new ArrayList<>();
		for (RemoteTarget target : targets) {
			targetNames.add(target.getName());
		}
		return targetNames.toArray(new String[0]);
	}
	
	public void addTarget(RemoteTarget target) {
		targets.add(target);
	}
	
	public void removeTarget(String targetName) {
		int index = -1;
		for (int i = 0; i < targets.size(); i++) {
			RemoteTarget target = targets.get(i);
			if (target.getName().equals(targetName)) {
				index = i;
				break;
			}
		}
		if (index != -1) {
			targets.remove(index);
		}
	}
	
	public RemoteTarget getTarget(String targetName) {
		for (RemoteTarget target : targets) {
			if (target.getName().equals(targetName)) {
				return target;
			}
		}
		
		return null;
	}
	
	public RemoteTarget getDefaultTarget() {
		for (RemoteTarget target : targets) {
			if (target.isDefault()) {
				return target;
			}
		}
		return this.targets.get(0);
	}
	
	public String toJsonString() {
		Gson gson = new Gson();
		return gson.toJson(this);
	}
	
	public TargetModel readJsonString(String json) {
		Gson gson = new Gson();
		return gson.fromJson(json, TargetModel.class);
	}
}
